const Service = require('egg').Service;
const svgCaptcha = require('svg-captcha');
var jwt = require('jsonwebtoken');
const md5 = require('js-md5');

class LoginService extends Service {
   // 生成验证码
   genCaptcha() {
      return svgCaptcha.create({
         width: 85,
         height: 38
      })
   }

   // 检查验证码是否正确
   checkCaptcha(code) {
      const {ctx} = this
      code = code.toLowerCase()
      let sessCode = ctx.session.code ? ctx.session.code.toLowerCase() : null // 拿到之前存在session中的验证码
      // 进行验证
      if (code === sessCode) {
         // 成功后验证码作废
         ctx.session.code = null
      }
      return code === sessCode
   }

   // 登录操作
   async login({username, password}) {
      const {ctx, app} = this
      try {
         const user = await ctx.model.User.findOne({
            where: {
               name: username.toString()
            },
         });
         if (!user) {
            return Object.assign(ERROR, {
               msg: 'username is error',
            });
         }
         if (md5(password) === user.password) {
            ctx.status = 200;
            const hash = md5.hex(password)
            console.log(hash);
            ctx.cookies.set('token', hash, {
               httpOnly: false,
               signed: false,
               maxAge: 3600 * 1000,
               path: '/',
            });
            ctx.cookies.set('user_id', user.id, {
               httpOnly: false,
               signed: false,
               maxAge: 3600 * 1000,
               path: '/',
            });
            // 找到则以用户id生成token
            const token = jwt.sign({
               id: userData[0]._id
            }, app.config.jwt.secret, {
               expiresIn: '10h' // token过期时间
            })
            return Object.assign(SUCCESS, {
               data: Object.assign(user, {
                  password: '',
               }),
               token: token
            });
         }
         return Object.assign(ERROR, {
            msg: 'password is error',
         });
      } catch (error) {
         ctx.status = 500;
         throw (error);
      }
   }
}

module.exports = LoginService
